<template>
  <view class="select-package">
    <up-navbar auto-back bg-color="transparent" />
    <view class="question">
      <uv-swiper :list="list" indicator keyName="image" indicatorMode="dot" indicatorActiveColor="#fff"
        :autoplay="true" circular imgMode="scaleToFill" height="720rpx" @click="clickSwiper" />
    </view>
    <view class="section">
      <!-- 类别选择 -->
      <view class="section-title">
        <image src="/static/select.png" class="search-icon" />
        <view>类别选择</view>
      </view>
      <view class="category-list">
        <view class="category-btn" :class="{ 'active': selectItem == idx }" v-for="(item, idx) in typeList" :key="idx"
          @click="selectType(idx,1)">{{ item.type_name }}</view>
      </view>

      <!-- 调酒容量规格 -->
      <view class="section-title">
        <image src="/static/select.png" class="search-icon" />
        <view>调酒容量规格</view>
      </view>
      <view class="section-count">
        <view class="category-btn b_50" :class="{ 'active': volumeItem == idx }" @click="selectType(idx,2)"
          v-for="(item, idx) in volumes" :key="idx">{{ item.sku }}ml</view>
      </view>

      <!-- 酒体选择 -->
      <view class="section-title" v-if="liquors.length!=0">
        <image src="/static/select.png" class="search-icon" />
        <view>酒体选择</view>
        <text class="desc">（总体调配和须达到100%）</text>
      </view>
      <view class="liquor-list">
        <view v-for="(item, idx) in liquors" :key="idx">
          <view class="liquor-item" @click="selectBody(item.id)">
            <view class="liquor-info" :class="{ 'liquor-active': item.isSelect}">
              <view v-if="item.show_json?.name == 1" class="liquor-title">{{ item.name || '-' }}</view>
              <view class="liquor-desc">
                <view v-if="item.show_json?.year == 1">年份：{{ item.year || '-' }}</view>
                <view v-if="item.show_json?.flavor == 1">风味特色：{{ item.flavor || '-' }}</view>
                <view v-if="item.show_json?.recommendRatio == 1">推荐调配占比：{{ item.min_percentage || 0 }} %-{{ item.max_percentage || 0 }} %</view>
                <view v-if="item.show_json?.price == 1">单价：{{ item.price||0 }}/500ml</view>
              </view>
            </view>
            <image v-show="!item.isSelect" :src="img(item.logo)" class="liquor-img" />
          </view>
          <view class="slider-row" v-if="item.isSelect">
            <view>
              <slider
                :value="item.percentage"
                :min="0"
                :max="100"
                :step="1"
                block-size="14"
                active-color="#FF0000"
                block-color="#FF0000"
                @change="onSliderChange(item, $event)"
                @changing="onSliderChanging(item, $event)"
                class="liquor-slider"
              />
              <view class="liquor-footer">
                <text style="font-weight: 500;">{{ item.percentage||0 }}</text>%
                <view class="line"></view>
                <text style="color: #FF0000;">￥{{ item.totalPrice?.toFixed(2)||0 }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 送样方式 -->
      <view v-if="liquors.length!=0">
        <view class="section-title">
          <image src="/static/select.png" class="search-icon" />
          <view>送样方式</view>
          <text class="desc-2" @click.stop="redirect({ url: '/app/pages/auth/agreement?key=alcohol_fx_gz' })">《{{agreement.title}}》</text>
        </view>
        <view class="section-count">
          <view class="category-btn b_50" :class="{ 'active': sendItem == idx }" v-for="(item, idx) in sendList"
            :key="idx" @click="selectType(idx,3)">{{ item }}</view>
        </view>
      </view>

      <!-- 定制容量规格 -->
      <view class="section-title" v-if="sendItem == 1">
        <image src="/static/select.png" class="search-icon" />
        <view>分装杯</view>
      </view>
      <view class="volume-row" v-if="sendItem == 1">
        <view class="volume-picker">
          <uv-input v-model="count" type="number" disabled-color="#ffffff" border="none" />
        </view>
        个
      </view>
    </view>

    <view class="back-arm">
      <view class="back-left">
        <view>合计：</view>
        <view class="price-text">
          <text style="font-size: 29rpx;">￥</text>
          <text>{{ parseFloat(totalPrice).toFixed(2).split('.')[0] }}</text>
          <text style="font-size: 29rpx;">.{{ parseFloat(totalPrice).toFixed(2).split('.')[1] }}</text>
        </view>
      </view>
      <view class="back-Right" @click="resetArm">
        <text>下一步</text>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import { ref, computed, nextTick } from 'vue';
  import { onLoad } from '@dcloudio/uni-app'
  import { redirect, img } from '@/utils/common'
  import { getBanner, getAlcoholtype, getAlcoholbody, getOther } from '@/addon/shop/api/select'
  import { getAgreementInfo } from '@/app/api/system'

  import useMemberStore from '@/stores/member'
  import { useLogin } from '@/hooks/useLogin'
  const memberStore = useMemberStore()
  const userInfo = computed(() => memberStore.info)
  const agreement = ref<any>({})
  const list = ref<any[]>([])
  const typeList = ref<any[]>([])
  const liquors = ref<any[]>([]);
  const sendList = ref<any[]>(['寄样', '分类寄样'])
  const volumes = ref<any[]>([]);
  const count = ref<any>(0);
  const volumeItem = ref<number>(0)
  const sendItem = ref<number>(0)
  const cup_price = ref<number>(0) // 分装杯单价
  const sendMoney = ref<number>(0)
  const alcohol_data = ref<any>({
    send_type: 1,
    alcohol_body: [],
    order_logo: []
  })


  onLoad((e) => {
    bannerList()
    getTypeList()
    getOtherList()
    getAgreement();
  })

  const selectItem = ref(0)

  const selectType = (idx: number, type: number) => {
    switch (type) {
      case 1:
        selectItem.value = idx
        alcohol_data.value.type_id = typeList.value[idx].id
        bodyList(typeList.value[idx].id)
        break
      case 2:
        volumeItem.value = idx
        let sku = volumes.value[volumeItem.value].sku
        alcohol_data.value.sku = sku
        sendMoney.value = parseFloat(volumes.value[volumeItem.value].delivery_money || '0')
        if (liquors.value.length != 0) {
          liquors.value.forEach(item => {
            if (item.isSelect) {
              item.totalPrice = item.price / 500 * sku * item.percentage / 100
            }
          })
        }
        break
      case 3:
        sendItem.value = idx
        alcohol_data.value.send_type = idx + 1
        if (idx == 1) {
          count.value = liquors.value.filter((item) => item.isSelect).length
        }
        break
    }
  }

  const resetArm = () => {
    if (!userInfo.value) {
        useLogin().setLoginBack({ url: '/addon/shop/pages/select/expertAdvice' })
        return false
    }
    let sum = 0
    for (const item of liquors.value) {
      if (item.isSelect) {
        sum += item.percentage
      }
    }
    if (sum != 100) {
      uni.showToast({ title: '调配和须达到100%', icon: 'none' })
      return
    }
    let num = liquors.value.filter((item) => item.isSelect).length
    if (sendItem.value == 1 && parseInt(count.value || '0') < num) {
      uni.showToast({ title: `分装杯至少为${num}个`, icon: 'none' })
      return
    }
    alcohol_data.value.cup_num = count.value
    alcohol_data.value.alcohol_body = liquors.value.filter(item => item.isSelect).map(item => {
      return {
        body_id: item.id,
        percentage: item.percentage
      }
    })
    uni.setStorage({
      key: 'orderCreateData',
      data: {
        alcohol_type: 1,
        alcohol_data: alcohol_data.value
      },
      success: () => {
        redirect({ url: '/addon/shop/pages/order/payment' })
      }
    });
  }

  // 计算总价
  const totalPrice = computed(() => {
    let cupPrice = sendItem.value == 0 ? 0 : cup_price.value * (Math.abs(count.value || 0)) // 分装杯价格
    return liquors.value.filter(item => item.isSelect).reduce((sum, item) => {
      return Number(sum) + Number(item.totalPrice.toFixed(2))
    }, 0) + sendMoney.value + cupPrice
  })

  const selectBody = (id: any) => {
    liquors.value.forEach(item => {
      if (item.id == id) {
        item.isSelect = !item.isSelect
        if (item.isSelect) {
          item.totalPrice = item.price / 500 * volumes.value[volumeItem.value].sku * item.percentage / 100
        } else {
          item.totalPrice = 0
          item.percentage = 0
        }
      }
    });
    count.value = liquors.value.filter((item) => item.isSelect).length
  }

  // 获取酒体
  const bodyList = (id: any) => {
    return getAlcoholbody(id).then((res: any) => {
      if (res.code == 1) {
        liquors.value = res.data.map((item: any) => {
          let list = item.change_percentage?.split(',').map((p: any) => Number(p)) || [];
          return {
            ...item,
            isSelect: false,
            percentageList: list,
            totalPrice: 0,
            percentage: snapToNearest(0, list),
            show_json: JSON.parse(item.show_json)
          }
        })
      }
    })
  }

  // 获取协议信息
  const getAgreement = () => {
    getAgreementInfo('alcohol_fx_gz').then((res: any) => {
      agreement.value = res.data
    })
  }

  // 获取轮播图 
  const bannerList = () => {
    getBanner().then((res: any) => {
      if (res.code == 1) {
        list.value = res.data.map((item: any) => {
          return {
            image: img(item.image),
            title: item.id
          }
        })
      }
    })
  }

  // 获取规格
  const getOtherList = () => {
    getOther().then((res: any) => {
      if (res.code == 1) {
        volumes.value = res.data.alcohol_sku ? JSON.parse(res.data.alcohol_sku) : []
        alcohol_data.value.sku = volumes.value[0].sku
        sendMoney.value = parseFloat(volumes.value[0].delivery_money || '0')
        cup_price.value = parseFloat(res.data.cup_price);
      }
    })
  }

  // 获取酒体分类
  const getTypeList = () => {
    getAlcoholtype().then((res: any) => {
      if (res.code == 1) {
        typeList.value = res.data
        alcohol_data.value.type_id = typeList.value[0].id
        bodyList(typeList.value[0].id)
      }
    })
  }

  // 点击图片预览
  const clickSwiper = (index: number) => {
    if(list.value[index].image.indexOf('mp4') != -1){
    } else {
      uni.previewImage({
        urls: list.value.map(item => item.image).filter(item => item.indexOf('mp4') == -1),
        current: index
      })
    }
  }

  // 改变滑动占比
  const onSliderChange = (item: any, e: any) => {
    const val = Number(e.detail.value);
    const nearValue = snapToNearest(val, item.percentageList);
    const currentSku = Number(volumes.value[volumeItem.value]?.sku || 0);
    item.totalPrice = Number(item.price || 0) / 500 * currentSku * Number(nearValue || 0) / 100;
    nextTick(() => {
      item.percentage = nearValue;
    })
  }

  // 滑动中
  const onSliderChanging = (item: any, e: any) => {
    const val = Number(e.detail.value);
    item.percentage = val;
  }
  
  // 计算最近可滑动点位
  const snapToNearest = (num: number, points: number[]) => {
    if (!points.length) return num;
    let closest = points[0];
    let minDiff = Math.abs(num - closest);
    for (let i = 1; i < points.length; i++) {
      const diff = Math.abs(num - points[i]);
      if (diff < minDiff) {
        minDiff = diff;
        closest = points[i];
      }
    }
    return closest;
  }
</script>

<style lang="scss" scoped>
  .select-package {
    min-height: 100vh;
    background: #f5f6fa;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-bottom: 110rpx;
  }

  .section {
    width: 100%;
    background: #fff;
    border-top-left-radius: 30px;
    border-top-right-radius: 30px;
    margin-bottom: 14px;
    padding: 30rpx 40rpx;
    box-sizing: border-box;
    margin-top: 660rpx;
    z-index: 9;

    .section-title {
      font-weight: bold;
      font-size: 17px;
      margin-bottom: 8px;
      margin-top: 6px;
      display: flex;
      align-items: center;

      .search-icon {
        width: 28rpx;
        height: 28rpx;
        margin-right: 8rpx;
        margin-top: 2rpx;
      }
    }

    .category-list {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      flex-wrap: wrap;
    }

    .section-count {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      flex-wrap: wrap;
    }
  }

  .b_50 {
    border-radius: 50rpx !important;
    padding: 14rpx 4rpx;

  }

  .back-arm {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 900;
    padding: 20rpx 40rpx;
    background: #fff;
    color: #fff;
    font-size: 30rpx;
    font-weight: 500;
    height: 86rpx;
    width: 88%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .back-Right {
      background: #fff;
      width: 27%;
      text-align: center;
      border-radius: 50rpx;
      height: 76rpx;
      line-height: 76rpx;
      color: #fff;
      background: linear-gradient(to right, #ff1919, #FF4000);
    }

    .back-left {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 26rpx;
      color: #3D3D3D;
      margin: 6rpx 0 0;

      view {
        color: #000;
      }

      .price-text {
        font-size: 38rpx;
        color: #FF0000;
      }
    }
  }

  .desc {
    color: #b1aeae;
    font-size: 13px;
    margin-left: 4rpx;
    margin-top: 3px;
  }
  .desc-2 {
    color: #f00;
    font-size: 13px;
    margin-left: 4rpx;
    margin-top: 3px;
  }

  .active {
    border: 2rpx solid #FF0000 !important;
    color: #FF0000 !important;
    background: #FDF0F0 !important;
  }

  .category-btn {
    width: 190rpx;
    background: #F1F1F1;
    color: #757575;
    border: 2rpx solid #F1F1F1;
    border-radius: 14rpx;
    text-align: center;
    font-size: 14px;
    padding: 15rpx 4rpx;
    margin: 10px 7px;
    box-sizing: border-box;
    transition: all 0.3s;
  }

  .liquor-list {
    width: 100%;

    .liquor-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      color: #757575;

      .liquor-info {
        flex: 1;
        max-width: 410rpx;
        height: 230rpx;
        margin-right: 10px;
        /* #ifdef H5 */
        padding: 10rpx 36rpx;
        /* #endif */
        /* #ifdef MP-WEIXIN */
        padding: 18rpx 36rpx;
        /* #endif */
        border-radius: 10px;
        box-sizing: border-box;
        transition: all 0.3s;
        color: #666;
        background: #f7f7f7;
        border: 2rpx solid #f7f7f7;
      }
      .liquor-active {
        height: auto !important;
        max-width: none !important;
        border: 2rpx solid #FF0000 !important;
        color: #FF0000 !important;
        background: #FDF0F0 !important;
        margin-right: 0 !important;
        .liquor-title, .liquor-desc > view {
          display: block !important;
        }
      }
      .liquor-img {
        width: 244rpx;
        height: 230rpx;
        border-radius: 8px;
        object-fit: cover;
      }

      .liquor-desc {
        font-size: 24rpx;
        line-height: 1.6;
        white-space: pre-line;
        > view {
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }
      }
    }

    .liquor-title {
      font-size: 16px;
      margin-bottom: 3px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
    }
  }

  .slider-row {
    background: #fff;
    border: 2rpx solid #E7E7E7;
    border-radius: 10px;
    margin-bottom: 18px;
    padding: 0 10px;
    transition: all 0.3s;

    .liquor-slider {
      width: 66%;
      margin: 9px 4px;

      .uni-slider-value {
        color: #000 !important;
      }
    }

    .liquor-footer {
      display: flex;
      justify-content: space-between;
      font-size: 15px;
      color: #333;

      .line {
        width: 1px;
        height: 34px;
        background: #E7E7E7;
        margin: 0 7px 0 15px;
      }
    }

    view {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }

  .volume-row {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-top: 10px;
    padding: 0 0 0 10px;

    .volume-picker {
      width: 126rpx;
      background: #Fff;
      border-radius: 30px;
      padding: 6px 12px;
      text-align: center;
      font-size: 16px;
      color: #757575;
      border: 2rpx solid #E7E7E7;
      margin-right: 20rpx;
    }
  }

  .package-list {
    margin-top: 12px;

    .package-title {
      font-size: 17px;
      margin: 10px 10px 8px;
      font-weight: bold;
    }

    .package-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;
    }

    .package-img {
      width: 120px;
      height: 90px;
      border-radius: 8px;
      margin-left: 4px;
      margin-top: 6px;
    }
  }

  .production {
    width: 100%;
    background: #fff;
    border-radius: 14px;
    margin-bottom: 14px;
    padding: 14rpx;
    box-sizing: border-box;
    padding-bottom: 0;

    .product-item {
      display: flex;
      align-items: flex-start;
      justify-content: flex-start;
    }

    .product-img {
      width: 100px;
      height: 100px;
      border-radius: 8px;
      margin-right: 26rpx;
    }

    .product-item-right {
      font-size: 34rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      height: 100px;
    }
  }

  .question {
    position: fixed;
    top: 0;
    width: 100%;
    padding: 0;
  }
  :deep(.uv-swiper__indicator) {
    bottom: 70rpx !important;
  }
</style>